#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time   : 2022-06-06 17:51:04
# @Author : 搬砖客

import os
from typing import Text
import yaml


# linux已经调试，没有问题
from common.path_setting import ensure_path_sep


class YamlUtil:

    # 读取一条用例,方法未使用
    @staticmethod
    def read_testcase_yaml_index(yaml_path: Text, index=0):
        """

        :param yaml_path: yaml文件地址
        :param index: 下标0表示第一条用例
        :return: 返回[dict]
        """
        with open(ensure_path_sep("\\data" + yaml_path), mode="r", encoding="utf-8") as file:
            result = yaml.load(file, Loader=yaml.FullLoader)[index]
            return result

    # 读取所有用例,方法未使用
    @staticmethod
    def read_testcase_yaml(yaml_path):
        with open(ensure_path_sep("\\data" + yaml_path), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data

    # 读取配置文件方法一
    @staticmethod
    def read_config_yaml(one_node, two_node):
        with open(ensure_path_sep("\\common\\config.yaml"), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data[one_node][two_node]

    # 读取配置文件方法一
    @staticmethod
    def read_mysql_config_yaml():
        with open(ensure_path_sep("\\common\\config.yaml"), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data['mysql']

    # 读取提取文件,通过key读取extract.yaml文件
    @staticmethod
    def read_extract_yaml(key):
        with open(ensure_path_sep("\\extract.yaml"), mode="r", encoding="utf-8") as file:
            data = yaml.load(file, Loader=yaml.FullLoader)
            return data[key]

    # 用于自动生成代码的时候读取
    @staticmethod
    def get_yaml_data(yaml_path) -> dict:
        """
        获取 yaml 中的数据
        :param: fileDir:
        :return:
        """
        # 判断文件是否存在
        if os.path.exists(yaml_path):
            data = open(yaml_path, 'r', encoding='utf-8')
            try:
                result = yaml.load(data, Loader=yaml.FullLoader)
                return result
            except UnicodeDecodeError:
                raise ValueError(f"yaml文件编码错误，文件路径:{yaml_path}")

        else:
            raise FileNotFoundError("文件路径不存在")

    # 将数据写入extract.yaml文件，如果键已经存在，会替换值
    @staticmethod
    def write_extract_yaml(data):
        from utils.logging_utils.log_util import write_log
        with open(ensure_path_sep("\\extract.yaml"), mode="r", encoding="utf-8") as file:
            old_result = yaml.safe_load(file)
            if old_result is not None:
                for key, value in dict(data).items():
                    if key in old_result:
                        write_log(f"键[{key}]已存在,他的值从[{old_result[key]}]替换为[{value}]")
                        old_result[key] = value
                        with open(ensure_path_sep("\\extract.yaml"), mode="w", encoding="utf-8") as replace_file:
                            data = yaml.dump(data=old_result, stream=replace_file, allow_unicode=True)
                    else:
                        with open(ensure_path_sep("\\extract.yaml"), mode="a", encoding="utf-8") as add_file:
                            data = yaml.dump(data=data, stream=add_file, allow_unicode=True)
            else:
                with open(ensure_path_sep("\\extract.yaml"), mode="a", encoding="utf-8") as add_file:
                    data = yaml.dump(data=data, stream=add_file, allow_unicode=True)
            return data
